package com.sky.service.impl;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;

import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.AddressOutBoundsException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.properties.ShopAddress;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.json.JSONArray;
import org.json.JSONObject;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
 public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper ;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    /**
     * 用户下单
     * @param ordersDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) throws Exception {
        //判断地址是否为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook==null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        String address =addressBook.getProvinceName()+addressBook.getCityName()
                +addressBook.getDistrictName()+addressBook.getDetail();

        //地址范围判断
        Map<String,Object> m = GETAddress(address);
        Integer integer = GETMile(m);
        System.out.println(integer);
        if (integer>5000){
            throw new AddressOutBoundsException(MessageConstant.ADDRESS_OUT_BOUNDS);
        }


        Long userId = Long.valueOf(4);
        Orders orders = new Orders();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        //查询当前用户的购物车数据，判断是否为空
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        //将电话，地址，收货人，订单号等封装到orders
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setUserId(userId);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setOrderTime(LocalDateTime.now());
        orderMapper.insert(orders);

        //将购物车信息封装到订单详情表
        List<OrderDetail> list =new ArrayList<OrderDetail>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            list.add(orderDetail);
        }
        orderDetailMapper.insert(list);

        //清理购物车中的数据
       shoppingCartMapper.cleanAll(userId);

        //封装返回结果

        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        return orderSubmitVO;
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = Long.valueOf(4);
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
               OrderPaymentVO vo = new OrderPaymentVO();
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = Long.valueOf(4);

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 历史订单查询
     * @param dto
     * @return
     */
    @Override
    public PageResult page(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<OrderVO> page = orderMapper.page(dto);
        //拼接字符串
        if (ObjectUtils.isNotEmpty(page.getResult())){
            page.getResult().forEach(orderVO -> {
                String collect = orderVO.getOrderDetailList().stream().map(x -> {
                    String orderDishs = x.getName() + "*" + x.getNumber() + ";";
                    return orderDishs;
                }).collect(Collectors.joining(""));
                orderVO.setOrderDishes(collect);
            });
        }
        long total = page.getTotal();

        return new PageResult(total,page.getResult());
    }
    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getById(Long id) {
        OrderVO orderVO = new OrderVO();
        Orders orders = orderMapper.getById(id);
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailMapper.getById(id));
        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancelById(Long id) {
        Orders orders = Orders.builder()
                        .id(id)
                        .status(Orders.CANCELLED)
                        .build();
        orderMapper.update(orders);
    }
    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetitionById(Long id) {
        List<OrderDetail> byId = orderDetailMapper.getById(id);
        shoppingCartMapper.cleanAll(4L);
        List<ShoppingCart> list = new ArrayList<>();
        for (OrderDetail orderDetail : byId) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(4L);
            shoppingCartMapper.insert(shoppingCart);
        }

    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO vo = new OrderStatisticsVO();
        vo.setConfirmed(orderMapper.count(Orders.CONFIRMED,4L));
        vo.setDeliveryInProgress(orderMapper.count(Orders.DELIVERY_IN_PROGRESS,4L));
        vo.setToBeConfirmed(orderMapper.count(Orders.TO_BE_CONFIRMED,4L));
        return vo;
    }

    /**
     * 接单
     * @param orders
     */
    @Override
    public void confirmById(Orders orders) {
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param dto
     */
    @Override
    public void rejection(OrdersRejectionDTO dto) {
        Orders byId = orderMapper.getById(dto.getId());
        if (byId.getStatus()!=Orders.TO_BE_CONFIRMED)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        BeanUtils.copyProperties(dto,byId);
        byId.setStatus(Orders.CANCELLED);
        orderMapper.update(byId);
    }
    /**
     * 取消订单
     * @param dto
     */
    @Override
    public void cancel(OrdersCancelDTO dto) {
        Orders byId = orderMapper.getById(dto.getId());
        if (byId.getStatus()!=Orders.CONFIRMED||byId.getStatus()!=Orders.DELIVERY_IN_PROGRESS||byId.getStatus()!=Orders.COMPLETED)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        BeanUtils.copyProperties(dto,byId);
        byId.setStatus(Orders.CANCELLED);
        orderMapper.update(byId);
    }
    /**
     * 派送订单
     * @param id
     *
     */
    @Override
    public void deliveryById(Long id) {
        Orders byId = orderMapper.getById(id);
        if (byId.getStatus()!=Orders.CONFIRMED)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        byId.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(byId);
    }
    /**
     * 完成订单
     * @param id
     *
     */
    @Override
    public void completeById(Long id) {
        Orders byId = orderMapper.getById(id);
        if (byId.getStatus()!=Orders.DELIVERY_IN_PROGRESS)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        byId.setStatus(Orders.COMPLETED);
        orderMapper.update(byId);
    }

    @Override
    public void reminderId(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    private Map<String,Object> GETAddress(String address) throws Exception{
        //创建HttpClient对象
        CloseableHttpClient aDefault = HttpClients.createDefault();
        //创建请求对象
        HttpGet httpGet = new HttpGet("https://api.map.baidu.com/geocoding/v3/?address="+address+
                "&output=json&ak=RDGbZGMIkKK8dcjH8iWY6ceDYDSo7yyz&output=json");
        //发送请求，接受响应结果
            CloseableHttpResponse response = aDefault.execute(httpGet);
            //获取服务器状态码
            //获取服务器返回的数据
            HttpEntity entity = response.getEntity();
            String body = EntityUtils.toString(entity);
            JSONObject jsonObject = new JSONObject(body);
            JSONObject result = jsonObject.getJSONObject("result");
            JSONObject location = result.getJSONObject("location");

        Map<String,Object> map = new HashMap<>();
        map.put("lng",location.get("lng"));
        map.put("lat",location.get("lat"));
        //关闭http资源
            response.close();
            aDefault.close();

        return map;
    }

    private Integer GETMile( Map<String,Object> map) throws Exception{
        //创建HttpClient对象
        CloseableHttpClient aDefault = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet("https://api.map.baidu.com/directionlite/v1/driving?" +
                "origin=40.05682848596073,116.3076223267197&destination="+map.get("lat")+","+map.get("lng") +
                "&ak=RDGbZGMIkKK8dcjH8iWY6ceDYDSo7yyz");
        //发送请求，接受响应结果
        CloseableHttpResponse response = aDefault.execute(httpGet);
        //获取服务器状态码
        int statusCode = response.getStatusLine().getStatusCode();//获取服务器返回的数据
        HttpEntity entity = response.getEntity();

        String body = EntityUtils.toString(entity);
        JSONObject jsonObject = new JSONObject(body);
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray routes = result.getJSONArray("routes");
        JSONObject jsonArray = routes.getJSONObject(0);
        Object distance = jsonArray.get("distance");
        Integer l = (Integer) distance;

        //关闭http资源
        response.close();
        aDefault.close();
        return l;
    }
}

